import { 
  AccountAPI, 
  SmsAPI, 
  UserAPI, 
  UserPropsAPI, 
  UserCapacityAPI, 
  CommonAPI, 
  LessonAPI 
} from './user.js'
import { setToken, setUserInfo, clearUserData } from '@/utils/auth'

/**
 * 用户登录相关示例
 */
export const LoginExamples = {
  // 手机验证码登录
  async phoneLoginByCode(phone, code) {
    try {
      const result = await AccountAPI.phoneLoginByCode({
        phone,
        code
      })
      
      if (result.code === 200) {
        // 保存token和用户信息
        setToken(result.data.token)
        setUserInfo(result.data.userInfo)
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })
        
        return result.data
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  },

  // 手机密码登录
  async phoneLoginByPassword(phone, password) {
    try {
      const result = await AccountAPI.phoneLoginByPassword({
        phone,
        password
      })
      
      if (result.code === 200) {
        setToken(result.data.token)
        setUserInfo(result.data.userInfo)
        return result.data
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  },

  // 第三方登录 - 微信
  async wechatLogin(wechatData) {
    try {
      const result = await AccountAPI.wechatLogin(wechatData)
      
      if (result.code === 200) {
        setToken(result.data.token)
        setUserInfo(result.data.userInfo)
        return result.data
      }
    } catch (error) {
      console.error('微信登录失败:', error)
      throw error
    }
  },

  // 退出登录
  async logout() {
    try {
      await AccountAPI.logout({})
      clearUserData()
      
      uni.showToast({
        title: '已退出登录',
        icon: 'success'
      })
    } catch (error) {
      console.error('退出登录失败:', error)
      // 即使请求失败，也清除本地数据
      clearUserData()
    }
  }
}

/**
 * 短信验证码相关示例
 */
export const SmsExamples = {
  // 发送登录验证码
  async sendLoginCode(phone) {
    try {
      const result = await SmsAPI.sendPhoneCode({ phone })
      
      if (result.code === 200) {
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
      }
      
      return result
    } catch (error) {
      console.error('发送验证码失败:', error)
      throw error
    }
  },

  // 发送绑定手机验证码
  async sendBindPhoneCode(phone) {
    try {
      const result = await SmsAPI.sendBindPhoneCode({ phone })
      
      if (result.code === 200) {
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
      }
      
      return result
    } catch (error) {
      console.error('发送绑定验证码失败:', error)
      throw error
    }
  }
}

/**
 * 用户信息管理示例
 */
export const UserInfoExamples = {
  // 获取用户信息
  async getUserInfo() {
    try {
      const result = await AccountAPI.getUserInfo({})
      return result.data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  },

  // 更新头像
  async updateAvatar(avatarUrl) {
    try {
      const result = await UserAPI.updateAvatar({ avatar: avatarUrl })
      
      if (result.code === 200) {
        uni.showToast({
          title: '头像更新成功',
          icon: 'success'
        })
      }
      
      return result.data
    } catch (error) {
      console.error('更新头像失败:', error)
      throw error
    }
  },

  // 更新昵称
  async updateNickname(nickname) {
    try {
      const result = await UserAPI.updateNickname({ nickname })
      
      if (result.code === 200) {
        uni.showToast({
          title: '昵称更新成功',
          icon: 'success'
        })
      }
      
      return result.data
    } catch (error) {
      console.error('更新昵称失败:', error)
      throw error
    }
  },

  // 绑定手机号
  async bindPhone(phone, code) {
    try {
      const result = await AccountAPI.bindPhone({ phone, code })
      
      if (result.code === 200) {
        uni.showToast({
          title: '手机号绑定成功',
          icon: 'success'
        })
      }
      
      return result.data
    } catch (error) {
      console.error('绑定手机号失败:', error)
      throw error
    }
  }
}

/**
 * 文件上传示例
 */
export const UploadExamples = {
  // 上传头像
  async uploadAvatar(filePath) {
    try {
      // 1. 获取预签名URL
      const preSignResult = await CommonAPI.uploadPreSign({
        fileName: `avatar_${Date.now()}.jpg`
      })
      
      if (preSignResult.code === 200) {
        // 2. 上传文件到OSS
        const uploadResult = await uni.uploadFile({
          url: preSignResult.data.uploadUrl,
          filePath,
          name: 'file',
          formData: preSignResult.data.formData
        })
        
        // 3. 更新用户头像
        const avatarUrl = preSignResult.data.fileUrl
        await UserInfoExamples.updateAvatar(avatarUrl)
        
        return avatarUrl
      }
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    }
  }
}

/**
 * 用户能力记录示例
 */
export const CapacityExamples = {
  // 创建能力记录
  async createCapacityRecord(recordData) {
    try {
      const result = await UserCapacityAPI.newRecord(recordData)
      
      if (result.code === 200) {
        uni.showToast({
          title: '记录创建成功',
          icon: 'success'
        })
      }
      
      return result.data
    } catch (error) {
      console.error('创建能力记录失败:', error)
      throw error
    }
  },

  // 查询能力记录
  async getCapacityRecords(queryParams) {
    try {
      const result = await UserCapacityAPI.myRecords(queryParams)
      return result.data
    } catch (error) {
      console.error('查询能力记录失败:', error)
      throw error
    }
  }
}

/**
 * 课程管理示例
 */
export const LessonExamples = {
  // 获取课程列表
  async getLessons(queryParams) {
    try {
      const result = await LessonAPI.getLessons(queryParams)
      return result.data
    } catch (error) {
      console.error('获取课程列表失败:', error)
      throw error
    }
  },

  // 更新课程
  async updateLesson(lessonData) {
    try {
      const result = await LessonAPI.lessonUpdate(lessonData)
      
      if (result.code === 200) {
        uni.showToast({
          title: '课程更新成功',
          icon: 'success'
        })
      }
      
      return result.data
    } catch (error) {
      console.error('更新课程失败:', error)
      throw error
    }
  }
}

/**
 * 地理位置服务示例
 */
export const LocationExamples = {
  // 解析地理位置
  async parseLocation(longitude, latitude) {
    try {
      const result = await CommonAPI.location({
        longitude,
        latitude
      })
      
      return result.data
    } catch (error) {
      console.error('解析地理位置失败:', error)
      throw error
    }
  }
}

/**
 * 完整的登录流程示例
 */
export const CompleteLoginFlow = {
  async login(phone, code) {
    try {
      // 1. 登录
      const loginResult = await LoginExamples.phoneLoginByCode(phone, code)
      
      // 2. 获取用户信息
      const userInfo = await UserInfoExamples.getUserInfo()
      
      // 3. 跳转到主页
      uni.switchTab({
        url: '/pages/index/index'
      })
      
      return {
        loginResult,
        userInfo
      }
    } catch (error) {
      console.error('登录流程失败:', error)
      throw error
    }
  }
}

export default {
  LoginExamples,
  SmsExamples,
  UserInfoExamples,
  UploadExamples,
  CapacityExamples,
  LessonExamples,
  LocationExamples,
  CompleteLoginFlow
} 